/**
 * Request 0.0.7
 * @Class uni-app request网络请求库
 * @Author lu-ch
 * @Date 2019-07-11
 * @Email webwork.s@qq.com
 * http://ext.dcloud.net.cn/plugin?id=392
 * **/
import qs from 'qs'
import constant from '@/constant/index'
import common from '@/utils/common'
import CONSTANT from '@/constant/index'

const Base64 = require('js-base64').Base64
class Request {
	config = {
		// #ifdef H5
		baseUrl: '/api',
		// #endif
		// #ifdef MP-WEIXIN
		baseUrl: constant.formal,
		// #endif
		header: {
			'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
		},
		data: {},
		method: 'GET',
		dataType: 'json',  /* 如设为json，会对返回的数据做一次 JSON.parse */
		responseType: 'text',
		success() { },
		fail() { },
		complete() { }
	}

	static posUrl(url) { /* 判断url是否为绝对路径 */
		return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
	}

	interceptor = {
		request: (f) => {
			if (f && typeof f === 'function') {
				this.requestBeforeFun = f
			}
		},
		response: (f) => {
			if (f && typeof f === 'function') {
				this.requestComFun = f
			}
		}
	}

	requestBeforeFun(config, cancel) {
		let token = ''
		try {
			const st = uni.getStorageSync('token')
			if (st) {
				token = st
			}
		} catch (e) {
			console.error(e, '获取token异常')
		}
		config.header = {
			...config.header,
			token, // 将token 放入header
			// WXAPPID: CONSTANT.oemObj.appid
			WXAPPID: uni.getAccountInfoSync().miniProgram.appId
		}
		// const token = uni.getStorageSync('token')
		// config.data = JSON.stringify(config.data);
		config.headers = {
			'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
		}
		// if (token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
		// 	// axios.defaults.headers.common['token'] = token;
		// 	config.headers.token = token
		// }
		// config.headers.HkdsRequestFrom = window.location.href
		// config.header.userRegion = Base64.encode(uni.getStorageSync('userRegion')) || null
		// config.header['x-client-hash'] = uni.getStorageSync('client_hash') || null
		const userRegion = Base64.encode(uni.getStorageSync('userRegion')) || null
		if (userRegion) {
			config.header.userRegion = userRegion
		}
		const clientHash = uni.getStorageSync('client_hash') || null
		if (clientHash) {
			config.header['x-client-hash'] = clientHash
		}
		if (config.config.loading) {
			uni.showLoading({
				title: '',
				mask: true
			})
		}
		return config
	}

	requestComFun(response) {
		if (response.config.config.loading) {
			uni.hideLoading()
		}
		// const client_hash = response.header.client_hash || response.header['X-Client-Hash']
		const client_hash = response.header.client_hash || ''
		// console.log('X-Client-Hash', response.header['X-Client-Hash'])
		if (client_hash) {
			uni.setStorageSync('client_hash', client_hash)
		}
		return response
	}

	setConfig(f) {
		this.config = f(this.config)
	}

	request(options = {}, config) {
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = Request.posUrl(options.url) ? options.url : (options.baseUrl + options.url)
		options.data = qs.stringify(options.data) || {}
		options.header = options.header || this.config.header
		options.method = options.method || this.config.method
		return new Promise((resolve, reject) => {
			let next = true
			let _config = null
			options.complete = (response) => {
				const statusCode = response.statusCode
				response.config = _config
				//   if(config.method === 'get') {
				// 	response.config.config = config
				//   }else if(config.method === 'post'){
				// 	response.config.config.config = config
				//   }
				response.config.config = config
				response = this.requestComFun(response)
				// 全局忽略错误，在单个请求里面自行处理
				if (config.hideError) {
					resolve(response.data)
				}
				if (statusCode === 200) { // 成功
					if (response.data.status === 'success') {
						resolve(response.data)
					} else {
						// 无权限或者登录过期
						// if (response.data.errors && response.data.errors.code === 400) {
						// 	uni.removeStorageSync('token')
						// 	uni.removeStorageSync('wxMobile')
						// 	uni.removeStorageSync('user_id')
						// 	uni.showToast({
						// 		title: '登陆过期，正在返回登录页...',
						// 		icon: 'none',
						// 		mask: true
						// 	})
						// 	setTimeout(() => {
						// 		uni.reLaunch({
						// 			url: `/pages/page/login/index`
						// 		})
						// 	}, 2000)
						// } else {
						if (!config.hideError) {
							uni.showToast({
								title: response.data.errors.message,
								icon: 'none',
								mask: true
							})
						}
						reject(response.data)
						// }
					}
				} else {
					reject(response)
				}
			}
			const cancel = (t = 'handle cancel') => {
				const err = {
					errMsg: t,
					config: afC
				}
				reject(err)
				next = false
			}
			const afC = { ...this.config, ...options, config: config }
			_config = { ...afC, ...this.requestBeforeFun(afC, cancel) }
			if (!next) return
			uni.request(_config)
		})
	}

	get(url, data, options = {}, config = {}) {
		options.url = url + common.queryData(data, true)
		options.data = {}
		options.method = 'GET'
		return this.request(options, config)
	}

	post(url, data, options = {}, config = {}) {
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options, config)
	}
}
export default new Request()

